package com.lemon.rpcframe.dao.basedao;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.log4j.Logger;

public class ConnectionHelper {

    private static Logger logger = Logger.getLogger(DBConnectionUtil.class);
    private final ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();

    private final BasicDataSource ds;

    public ConnectionHelper(String path) {
        String url = "jdbc:mysql://192.168.120.73:3306/dbwww58com_distask?connectTimeout=1000&useUnicode=true&characterEncoding=utf-8";
        ds = new BasicDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUsername("root");
        ds.setPassword("zhaopin5678");
        ds.setTestOnBorrow(true);
        ds.setUrl(url);
        ds.setMaxActive(3);
        ds.setMaxIdle(6);
        ds.setMinIdle(6);
        ds.setMaxWait(60 * 1000);

        logger.info("Create new connection for " + " with url=" + url);
    }

    /**
     * 获取一个写连接
     * @return
     * @throws SQLException
     * @throws IOException
     */
    public Connection get() throws SQLException, IOException {
        Connection conn = null;
        try {
            conn = ds.getConnection();
            return conn;
        } catch (Exception e) {
            throw new SQLException("no idle connection: " + e.getLocalizedMessage());
        }
    }

    /**
     * 获取一个只读连接
     * @return 
     * @throws SQLException
     * @throws IOException
     */
    public Connection getReadConnection() throws SQLException, IOException {
        Connection conn = null;
        try {
            conn = ds.getConnection();
            return conn;
        } catch (Exception e) {
            throw new SQLException("no idle connection: " + e.getLocalizedMessage());
        }
    }

    /**
     * 归还连接
     */
    public void release(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ex) {
            }
        }
    }

    public void lockConn(Connection conn) {
        threadLocal.set(conn);
    }

    public void unLockConn() {
        threadLocal.set(null);
    }

}
